﻿Namespace Socket.HTTPStats.Data

    Public Class OnlineUsers

        Private Shared lstUsers As New List(Of PlayerOnlineInfo)
        Private Shared objLock As New Object

        Public Shared ReadOnly Property OnlineUsersString() As String
            Get
                SyncLock objLock
                    If lstUsers.Count > 0 Then
                        Dim ret As String = ""
                        For Each user As PlayerOnlineInfo In lstUsers
                            ret &= user.STR_NAME & "<br />" & vbCrLf
                        Next
                        Return Left(ret, ret.Length - 8)
                    Else
                        Return "there are no users currently playing"
                    End If
                End SyncLock
            End Get
        End Property

        Public Shared Sub Online(info As PlayerOnlineInfo)

            SyncLock objLock

                lstUsers.Add(info)

            End SyncLock

        End Sub

        Public Shared Sub Offline(info As PlayerOnlineInfo)

            SyncLock objLock

                If lstUsers.Count = 0 Then Exit Sub

                Dim usr As PlayerOnlineInfo

                For i As Integer = 0 To lstUsers.Count - 1

                    usr = lstUsers(i)

                    If usr.ID_CHARACTER = info.ID_CHARACTER Then
                        lstUsers.RemoveAt(i)
                        Exit Sub
                    End If

                Next

            End SyncLock

        End Sub

        Public Shared Function isOnline(id As Int64) As Boolean

            SyncLock objLock

                For Each usr As PlayerOnlineInfo In lstUsers

                    If usr.ID_CHARACTER = id Then
                        Return True
                    End If

                Next

                Return False

            End SyncLock

        End Function

        Public Shared Function isOnline(name As String) As Boolean

            SyncLock objLock

                For Each usr As PlayerOnlineInfo In lstUsers

                    If LCase(usr.STR_NAME) = LCase(name) Then
                        Return True
                    End If

                Next

                Return False

            End SyncLock

        End Function

        Public Shared Sub RefreshNewServer()

            Dim pkt As New Packet
            pkt.Username = Globals.ServerName
            pkt.PacketType = InterServerPacketType.UserLogin
            pkt.PacketOpCode = PacketOpCode.Notify
            
            SyncLock objMapsLock

                For Each ulogin As PlayerOnlineInfo In lstUsers

                    Socket.ClusterComms.UDPBrocast.SendData(Protocol.MakePacket(pkt, ulogin))

                Next

            End SyncLock

        End Sub

    End Class

End Namespace